from flask_restplus import Namespace, Resource, fields
from flask import request
from app.models import db, Book, User, OwnBook, HopeBook, ShareRecord
from .auth import auth

api = Namespace("book", description="书籍资源类")

doc = {
    'description': '接口未开发',  # 描述
    # 'responses': {403: 'forbidden', 404: 'page not found'},     # 响应
    'deprecated': True  # 是否废弃
}

doc1 = {

    'params': {'bid': '书籍id'},
    'description': '书籍详细信息',  # 描述
    'responses': {403: 'forbidden', 404: 'page not found'},  # 响应
    # 'deprecated': True  # 是否废弃
}

doc2 = {
    'params': {'page': "第几页的数据", "per_page": "每页的数据量"},
    'description': '书籍展示',  # 描述
    'responses': {403: 'forbidden', 404: 'page not found'},
}

model2 = api.model('resp1', {
    'page': fields.Integer,
    'per_page': fields.Integer(discriminator=True)
})

doc3 = {
    'params': {'q': "搜索内容"},
    'description': '书籍搜索',  # 描述
    'responses': {403: 'forbidden'},
}

doc4 = {
    'params': {'hopername': "想要书的人的昵称", "bid": "书籍的id"},
    'description': '想要书籍',  # 描述
    'responses': {403: 'forbidden', 404: 'page not found', 200: 'success'},
}

model3 = api.model('resp2', {
    'hopername': fields.String
})

doc5 = {
    'params': {'bid': "书籍的id", "send": "赠送人的昵称", "receive": "想要书人的昵称"},
    'description': '赠送书籍',  # 描述
    'responses': {403: 'forbidden', 404: 'page not found', 200: 'success'},
}

model4 = api.model('resp3', {
    'send': fields.String,
    'receive': fields.String
})


# doc：添加接口文档信息
@api.route('/<int:bid>/')
class BookAPI(Resource):
    @api.doc(**doc1)
    @api.response(200, 'success', headers={"name": "书名", "year": "出版年月", "page": "页数", "money": "售价", "ISBN": "ISBN",
                                           "description": "简介"})
    def get(self, bid):
        book = Book.query.get_or_404(bid)
        return {"name": book.name, "year": str(book.year), "page": book.page, "money": book.money, "ISBN": book.ISBN,
                "description": book.description}

    @api.doc(**doc)
    def put(self, bid):
        return {"ApiNoUse": "Undevelop"}

    @api.doc(**doc)
    def delete(self, bid):
        return {"ApiNoUse": "Undevelop"}


@api.route('/')
# 给整个资源添加接口文档信息
# @api.doc(**doc)
class BookListAPI(Resource):
    # 给指定接口添加说明文档
    @api.doc(**doc2)
    @api.expect(model2)
    @api.response(200, 'success', headers={"name": "书名", "ISBN": "ISBN", "description": "简介"})
    @api.response(402, "Error",
                  headers={"Error1": "不能输入零页", "Error2": "每页数据不能为零", "Error3": "页码超出范围"})
    def get(self):
        page = request.json.get("page")
        per_page = request.json.get("per_page")
        if not page:
            return {"Error1": "PageEmpty"}
        if not per_page:
            return {"Error2": "Per_pageEmpty"}
        Pagination = Book.query.paginate(page=page, per_page=per_page, error_out=False)
        pages = Pagination.pages
        if page > pages:
            return {"Error3": "Data is empty"}
        books = Pagination.items
        data_list = []
        for b in books:
            data_list.append({"name": b.name, "ISBN": b.ISBN, "description": b.description})
        return data_list

    @api.doc(**doc)
    def post(self):
        return {"ApiNoUse": "Undevelop"}


@api.route("/search/")
class book(Resource):
    @api.doc(**doc3)
    @api.response(200, 'success', headers={"name": "书名", "ISBN": "ISBN"})
    @api.response(404, 'page_not_found', headers={"Error": "book not exist"})
    def get(self):
        info = request.args.get("q")
        book = Book.query.filter_by(ISBN=info).first()
        if book:
            return [{"bookname": book.name}]
        else:
            books = Book.query.filter(Book.name.ilike('%' + info + '%')).all()
            if not books:
                return {"Error": "book not exist"}
            book_list = []
            for i in books:
                book_list.append({"bookname": i.name, "ISBN": i.ISBN})
            return book_list


@api.route("/<int:bid>/want/")
@api.doc(**doc4)
@api.expect(model3)
class WantBook(Resource):
    @auth.login_required
    @api.response(200, 'success', headers={"Success": "请求成功"})
    @api.response(402, 'Error', headers={"Error": "你已经有这本书"})
    def put(self, bid):
        hopername = request.json.get("hoper")
        hoper = User.query.filter_by(nikename=hopername).first()
        book = Book.query.get(bid)
        print(hoper.id, bid)
        if OwnBook.query.filter_by(uid=hoper.id, bid=bid).first():
            return {"Error": "User_Own"}
        db.session.add(HopeBook(bid=bid, uid=hoper.id))
        return {"Success": "Append_Wish"}


@api.route("/<int:bid>/share/")
@api.doc(**doc5)
@api.expect(model4)
class ShareBook(Resource):
    @auth.login_required
    @api.response(200, 'success', headers={"Success": "Send_Success"})
    @api.response(402, "Error",
                  headers={"Error1": "赠书人自己没有这本书", "Error2": "不需要重复赠送", "Error3": "请求人已经有这本书"})
    def put(self, bid):
        send = request.json.get("send")
        receive = request.json.get("receive")
        book = Book.query.get_or_404(bid)
        hoper = User.query.filter_by(nikename=receive).first()
        sender = User.query.filter_by(nikename=send).first()
        delhoper = HopeBook.query.filter_by(uid=hoper.id).first()
        if not OwnBook.query.filter_by(uid=sender.id, bid=bid).first():
            return {"Error1": "sender no have book"}
        print(send, receive, book.name)
        print(ShareRecord.query.filter_by(send=send, receive=receive, bookname=book.name).first())
        if ShareRecord.query.filter_by(send=send, receive=receive, bookname=book.name).first():
            return {"Error2": "share_record_exist"}
        db.session.add(ShareRecord(send=send, receive=receive, bookname=book.name))
        if OwnBook.query.filter_by(uid=hoper.id, bid=bid).first():
            return {"Error3": "own_book_exist"}
        db.session.add(OwnBook(uid=hoper.id, bid=bid))
        db.session.delete(delhoper)
        return {"Success": "Send_Success"}
